package itsen.com.bduidemo.modle.net;

import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Looper;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.gson.Gson;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.ObservableSource;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.functions.Predicate;
import itsen.com.bduidemo.R;
import itsen.com.bduidemo.common.activity.BaseAppActivity;
import itsen.com.bduidemo.lib.net.ProgressListener;
import itsen.com.bduidemo.lib.net.ProgressResponseBody;
import itsen.com.bduidemo.lib.net.SSLHelper;
import itsen.com.bduidemo.lib.net.UnSafeHostnameVerifier;
import itsen.com.bduidemo.lib.net.rxretrofit.RetrofitManager;
import itsen.com.bduidemo.lib.thread.ThreadPool;
import itsen.com.bduidemo.lib.tool.LogTool;
import itsen.com.bduidemo.lib.tool.ToastTool;
import itsen.com.bduidemo.lib.util.IPutils;
import itsen.com.bduidemo.modle.net.been.Customer;
import itsen.com.bduidemo.modle.net.been.Items;
import itsen.com.bduidemo.modle.net.retrofit2.ItemLoader;
import itsen.com.bduidemo.modle.net.retrofit2.ItemsBiz;
import itsen.com.bduidemo.modle.net.retrofit2.WeatherInterfaceApi;
import itsen.com.bduidemo.modle.net.webservice.RetrofigWebservice;
import itsen.com.bduidemo.modle.net.webservice.request.RequestEnvelope;
import itsen.com.bduidemo.modle.net.webservice.request.RequestModel;
import itsen.com.bduidemo.modle.net.webservice.respone.ResponseEnvelope;
import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class NetActivity extends BaseAppActivity {
    String baseUrl = IPutils.getIP2();
    final static String FORADN = "ForAnd/";
    @BindView(R.id.text_show)
    TextView textShow;
    @BindView(R.id.iv_show_pic)
    ImageView ivShowPic;
    @BindView(R.id.ly_file)
    LinearLayout lyFile;
    private Gson gson;
    private HttpLoggingInterceptor loggingInterceptor;
    private OkHttpClient client;
    private long mTimeOut = 8000;
    private Retrofit retrofit;
    private ItemLoader itemLoader;
    /***
     * 使用照相机拍照获取图片
     */
    public static final int SELECT_PIC_BY_TACK_PHOTO = 1;
    /***
     * 使用相册中的图片
     */
    public static final int SELECT_PIC_BY_PICK_PHOTO = 2;

    /***
     * 从Intent获取图片路径的KEY
     */
    public static final String KEY_PHOTO_PATH = "photo_path";
    private Uri photoUri;
    /**
     * 获取到的图片路径
     */
    private String picPath;


    @Override
    public int getLayoutId() {
        return R.layout.activity_net;
    }

    @Override
    public void initData() {
        //封装模式
        itemLoader = new ItemLoader();

        gson = new Gson();
        //日志
        loggingInterceptor = new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
            @Override
            public void log(String message) {
                //打印retrofit日志
                Log.i("RetrofitLog", "retrofitBack = " + message);
            }
        });

        //日志等级
        loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);

        //参数配置
        client = new OkHttpClient.Builder()
                .sslSocketFactory(SSLHelper.getSSLCertifcation(this))
                .hostnameVerifier(new UnSafeHostnameVerifier())
                .addInterceptor(loggingInterceptor)
                .connectTimeout(mTimeOut, TimeUnit.SECONDS)
                .readTimeout(mTimeOut, TimeUnit.SECONDS)
                .writeTimeout(mTimeOut, TimeUnit.SECONDS)
                .build();

        //retrofit 对象初始化
        retrofit = new Retrofit.Builder()
                .baseUrl(baseUrl + FORADN)
                .addConverterFactory(GsonConverterFactory.create())
                .client(client)
                .build();
    }

    /**
     * POST/GET  简单
     */
    private void doGet() {
        //ItemsBiz itemsBiz = retrofit.create(ItemsBiz.class);
        ItemsBiz itemsBiz =  RetrofitManager.getInstance().create(ItemsBiz.class);
        Call<Items> call = itemsBiz.getItems();
        call.enqueue(new Callback<Items>() {
            @Override
            public void onResponse(Call<Items> call, Response<Items> response) {
                textShow.setText(gson.toJson(response.body()));
            }

            @Override
            public void onFailure(Call<Items> call, Throwable t) {
                t.printStackTrace();
            }
        });

       /* itemsBiz.getItemsRx().subscribe(new Consumer<Items>() {
            @Override
            public void accept(Items items) throws Exception {

            }
        });*/

    }

    /**
     * Path  {"占位符"}
     */
    private void doPost() {
        ItemsBiz itemsBiz = retrofit.create(ItemsBiz.class);
        Call<Items> call = itemsBiz.getItemsPost(19, "zhou");
        call.enqueue(new Callback<Items>() {
            @Override
            public void onResponse(Call<Items> call, Response<Items> response) {
                textShow.setText(gson.toJson(response.body()));
            }

            @Override
            public void onFailure(Call<Items> call, Throwable t) {

            }
        });
    }

    /**
     * Query
     */
    private void doPostQuery() {
        ItemsBiz itemsBiz = retrofit.create(ItemsBiz.class);
        Call<Items> call = itemsBiz.getItemsQurey("zhou", 10);
        call.enqueue(new Callback<Items>() {
            @Override
            public void onResponse(Call<Items> call, Response<Items> response) {
                textShow.setText(gson.toJson(response.body()));
            }

            @Override
            public void onFailure(Call<Items> call, Throwable t) {

            }
        });
    }

    /**
     * 模拟表单 FormUrlEncoded Field
     */
    private void doPostForm() {
        ItemsBiz itemsBiz = retrofit.create(ItemsBiz.class);
        Call<Items> call = itemsBiz.getItemsForm("zhou", 10);
        call.enqueue(new Callback<Items>() {
            @Override
            public void onResponse(Call<Items> call, Response<Items> response) {
                textShow.setText(gson.toJson(response.body()));
            }

            @Override
            public void onFailure(Call<Items> call, Throwable t) {

            }
        });
    }

    /**
     * json 交互
     */
    private void doPostJson() {
        Items items = new Items();
        items.setDetail("json交互");
        items.setId(10);
        ItemsBiz itemsBiz = retrofit.create(ItemsBiz.class);
        Call<Items> call = itemsBiz.getItemsJson(items);
        call.enqueue(new Callback<Items>() {
            @Override
            public void onResponse(Call<Items> call, Response<Items> response) {
                textShow.setText(gson.toJson(response.body()));
            }

            @Override
            public void onFailure(Call<Items> call, Throwable t) {

            }
        });
    }

    // /storage/emulated/0/DCIM/Camera/IMG_20171231_172618.jpg
    public void upload() {
        Retrofit retrofit2 = new Retrofit.Builder()
                .baseUrl(baseUrl + FORADN)
                .client(client)
                .build();
        ItemsBiz itemsBiz = retrofit2.create(ItemsBiz.class);
        File file = new File(picPath);
        if (file.exists()) {
            ToastTool.showLong("图片存在");
        }
        RequestBody photoRequestBody = RequestBody.create(MediaType.parse("multipart/form-data"), file);
        MultipartBody.Part photo = MultipartBody.Part.createFormData("image", file.getName(), photoRequestBody);

        Call<ResponseBody> call = itemsBiz.upload(photo);
        call.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                textShow.setText(response.body().toString());
                lyFile.setVisibility(View.GONE);
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                textShow.setText(t.toString());
                t.printStackTrace();
            }

        });
    }

    //监听进度
    public void upload2(){
        OkHttpClient client = new OkHttpClient.Builder()
                .addNetworkInterceptor(new Interceptor() {
                    @Override
                    public okhttp3.Response intercept(Chain chain) throws IOException {
                        okhttp3.Response orginalResponse = chain.proceed(chain.request());

                        return orginalResponse.newBuilder()
                                .body(new ProgressResponseBody(orginalResponse.body(), new ProgressListener() {
                                    @Override
                                    public void onProgress(long progress, long total, boolean done) {
                                        textShow.setText("进度：" + progress);
                                        Log.e("pr", Looper.myLooper() + "");
                                        Log.e("pr", "onProgress: " + "total ---->" + total + "done ---->" + progress);
                                    }
                                }))
                                .build();
                    }
                })
                .build();

        Retrofit retrofit2 = new Retrofit.Builder()
                .baseUrl(baseUrl + FORADN)
                .client(client)
                .build();
        ItemsBiz itemsBiz = retrofit2.create(ItemsBiz.class);
        File file = new File(picPath);
        if (file.exists()){
            ToastTool.showLong("图片存在");
        }
        RequestBody photoRequestBody = RequestBody.create(MediaType.parse("multipart/form-data"), file);
        MultipartBody.Part photo = MultipartBody.Part.createFormData("image", file.getName(), photoRequestBody);

        Call<ResponseBody> call = itemsBiz.upload(photo);
        call.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                textShow.setText(response.body().toString());
                lyFile.setVisibility(View.GONE);
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                textShow.setText(t.toString());
                t.printStackTrace();
            }

        });
    }

    private void rxRetrofit() {
        itemLoader.getItems(5).subscribe(new Consumer<List<Items>>() {
            @Override
            public void accept(List<Items> items) throws Exception {
                for (int i = 0; i < items.size(); i++) {

                }
            }
        });


    }

    private void rxRetrofit2() {
        itemLoader.getCustomers(3).flatMap(new Function<List<Customer>, ObservableSource<Customer>>() {
            @Override
            public ObservableSource<Customer> apply(List<Customer> customers) throws Exception {
                return Observable.fromIterable(customers);
            }
        }).filter(new Predicate<Customer>() {
            @Override
            public boolean test(Customer customer) throws Exception {
                return customer.getId() == 1;
            }
        }).subscribe(new Consumer<Customer>() {
            @Override
            public void accept(Customer customer) throws Exception {
                textShow.setText(gson.toJson(customer));
            }
        });
    }

    @OnClick({R.id.btn_get, R.id.btn_post_1, R.id.btn_post_2, R.id.btn_post_form, R.id.btn_post_json, R.id.btn_file, R.id.btn_start_upload, R.id.btn_ws, R.id.btn_ok, R.id.btn_rxjava})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_get:
                doGet();
                break;
            case R.id.btn_post_1:
                doPost();
                break;
            case R.id.btn_post_2:
                doPostQuery();
                break;
            case R.id.btn_post_form:
                doPostForm();
                break;
            case R.id.btn_post_json:
                doPostJson();
                break;
            case R.id.btn_file:
                pickPhoto();
                break;
            case R.id.btn_start_upload:
                //upload();
                upload2();
                break;
            case R.id.btn_ws:
                webervice();
               /* ThreadPool.getmFixedThreadPool().submit(new Runnable() {
                    @Override
                    public void run() {
                        queryW();
                    }
                });*/
                break;
            case R.id.btn_ok:
                okhttpTest();
                break;
            case R.id.btn_rxjava:
                rxRetrofit2();
                break;

            default:

                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == SELECT_PIC_BY_PICK_PHOTO)  //从相册取图片，有些手机有异常情况，请注意
        {
            if (data == null) {
                ToastTool.showLong("选择图片文件出错");
                return;
            }
            photoUri = data.getData();
            if (photoUri == null) {
                ToastTool.showLong("选择图片文件出错");
                return;
            }

            String[] pojo = {MediaStore.Images.Media.DATA};
            Cursor cursor = managedQuery(photoUri, pojo, null, null, null);
            if (cursor != null) {
                int columnIndex = cursor.getColumnIndexOrThrow(pojo[0]);
                cursor.moveToFirst();
                picPath = cursor.getString(columnIndex);
                if (Build.VERSION.SDK_INT < 14) {
                    cursor.close();
                }
            }
            LogTool.e(picPath);
            if (picPath != null && (picPath.endsWith(".png") || picPath.endsWith(".PNG") || picPath.endsWith(".jpg") || picPath.endsWith(".JPG"))) {
                lyFile.setVisibility(View.VISIBLE);
                Bitmap bm = BitmapFactory.decodeFile(picPath);
                ivShowPic.setImageBitmap(bm);
            } else {
                lyFile.setVisibility(View.GONE);
                ToastTool.showLong("选择图片文件不正确");
            }
        }
    }


    /***
     * 从相册中取图片
     */
    private void pickPhoto() {
        Intent intent = new Intent();
        intent.setType("image/*");
        intent.setAction(Intent.ACTION_GET_CONTENT);
        startActivityForResult(intent, SELECT_PIC_BY_PICK_PHOTO);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    //参考：https://blog.csdn.net/yjp19871013/article/details/67632305
    //命名空间
    private static final String serviceNameSpace = "http://itsen.com/";
    //调用方法
    private static final String qureyWhter = "qureyWhter";

    private void queryW() {
        SoapCommunicator soapCommunicator = new SoapCommunicator();
        Map<String, Object> params = new HashMap<>();
        params.put("ciryName", "上海");
        //这里使用的局域网，要保证IP可访问
        final String ret = soapCommunicator.call(
                "http:/192.168.0.27:8080/?wsdl",
                serviceNameSpace,
                qureyWhter,
                params
        );
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                textShow.setText(ret);
            }
        });
    }

    private void okhttpTest() {
        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .sslSocketFactory(SSLHelper.getSSLCertifcation(this))
                .hostnameVerifier(new UnSafeHostnameVerifier())
                .build();
        Request request = new Request.Builder()
                .url(IPutils.getIP2() + FORADN + "items.action")
                .get()
                .build();

        okhttp3.Call call = okHttpClient.newCall(request);

        call.enqueue(new okhttp3.Callback() {
            @Override
            public void onFailure(okhttp3.Call call, IOException e) {
                //TODO failure
            }

            @Override
            public void onResponse(okhttp3.Call call, okhttp3.Response response) throws IOException {
                //TODO success
                textShow.setText(response.body().string());
            }
        });
    }

    private void webervice(){
        RequestEnvelope requestEnvelop = new RequestEnvelope();
        itsen.com.bduidemo.modle.net.webservice.request.RequestBody requestBody = new itsen.com.bduidemo.modle.net.webservice.request.RequestBody ();
        RequestModel requestModel = new RequestModel();
        requestModel.theCityName = "上海";
        requestModel.cityNameAttribute = "http://WebXml.com.cn/";
        requestBody.getWeatherbyCityName = requestModel;
        requestEnvelop.body = requestBody;
        WeatherInterfaceApi interfaceApi = RetrofigWebservice.getInstance().setCreate(WeatherInterfaceApi.class);
        Call<ResponseEnvelope> call = interfaceApi.getWeatherbyCityName(requestEnvelop);
        call.enqueue(new Callback<ResponseEnvelope>() {
            @Override
            public void onResponse(Call<ResponseEnvelope> call, Response<ResponseEnvelope> response) {
                ResponseEnvelope responseEnvelope = response.body();
                if (responseEnvelope != null ) {
                    List<String> weatherResult = responseEnvelope.body.getWeatherbyCityNameResponse.result;
                    textShow.setText(gson.toJson(weatherResult));
                }
            }

            @Override
            public void onFailure(Call<ResponseEnvelope> call, Throwable t) {

            }
        });
    }

    /**
     * okhttp 返回实例
     */
    private void requstOkhttp(){
        OkHttpClient okHttpClient = new OkHttpClient();

        final Request request = new Request.Builder()
                .url("https://www.xxx.com/xxx")
                .addHeader("key","value")
                .build();


        //同步方式
        try {

            okhttp3.Response response = client.newCall(request).execute();

        } catch (IOException e) {
            e.printStackTrace();
        }


        //异步方式
        okhttp3.Call call = okHttpClient.newCall(request);

        call.enqueue(new okhttp3.Callback() {
            @Override
            public void onFailure(okhttp3.Call call, IOException e) {
                //TODO 请求失败回掉
            }

            @Override
            public void onResponse(okhttp3.Call call, okhttp3.Response response) throws IOException {
                //TODO 服务器返回数据
            }
        });
    }
}
